package com.qf.controller;

import com.qf.controller.utils.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * author:z
 * time:2021/12/24 11:25
 * description:
 */
@RestController
@RequestMapping("/redis")
public class TestRedisController {

    //1. 准备商品的库存
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2. 准备商品的订单
    public static Map<String,Integer> itemOrder = new HashMap<>();

    static {
        itemStock.put("牙刷",1000);
        itemOrder.put("牙刷",0);
    }

    @Autowired
    CuratorFramework client;

    @Autowired
    RedisLockUtil redisLockUtil;

    @RequestMapping("/kill")
    public String kill(String item) throws Exception {
        if(redisLockUtil.lock(item,System.currentTimeMillis()+"",5)){
            //减库存 判断是否有库存
            Integer stock = itemStock.get("牙刷");
            if(stock<=0){
                return item+"卖完了====="+item+"还剩下:"+itemStock.get(item);
            }
            Thread.sleep(100);
            //库存减一
            itemStock.put(item,itemStock.get(item)-1);

            //增加订单
            Thread.sleep(100);
            itemOrder.put(item,itemOrder.get(item)+1);

            redisLockUtil.unlock(item);
        }


        return item+"还剩下"+itemStock.get(item)+"已卖"+item+":"+itemOrder.get(item);
    }
}
